package cn.zch.cmbchina.util.cmb;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.X509EncodedKeySpec;
public class SignCmb {
  /**
   * @param strToSign String
   * @param strSign String
   * @param publicKey String
   * @return boolean
   */
  public static boolean isValidSignature(String strToSign, String strSign, String publicKey) {
    try {
      KeyFactory keyFactory = KeyFactory.getInstance("RSA");
      byte[] encodedKey = Base64.decode(publicKey);
      PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
      java.security.Signature signature = java.security.Signature.getInstance("SHA1WithRSA");
      signature.initVerify(pubKey);
      signature.update(strToSign.getBytes(StandardCharsets.UTF_8));
      boolean verify = signature.verify(Base64.decode(strSign));
      System.out.println("verify = " + verify);
      return verify;
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
  /**
   * DES加密示例
   */
  public static byte[] DesEncrypt(byte[] plain, byte[] key) {
    try {
      SecureRandom random = new SecureRandom();
      DESKeySpec desKeySpec = new DESKeySpec(key);
      //创建一个密匙工厂，然后用它把DESKeySpec转换成
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
      SecretKey securekey = keyFactory.generateSecret(desKeySpec);
      //Cipher对象实际完成加密操作
      Cipher cipher = Cipher.getInstance("DES");//DES/ECB/PKCS5Padding
      //用密匙初始化Cipher对象
      cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
      //现在，获取数据并加密
      //正式执行加密操作
      return cipher.doFinal(plain);
    }
    catch (Throwable e) {
      e.printStackTrace();
    }
    return null;
    //    //调用
    //    try
    //    {
    //      byte[] byteKey = desKey.getBytes("UTF-8");
    //      byte[] byteBodyContent = sBodyContent.getBytes("UTF-8");
    //      byte[] baCiphertext = TestDes.DesEncrypt(byteBodyContent, byteKey);
    //      //将byte转为16进制字符串
    //    } catch(
    //      UnsupportedEncodingException e)
    //    {
    //      // TODO Auto-generated catch block
    //      e.printStackTrace();
    //    }
  }
  /**
   * sign
   */
  public static String getSign(StringBuilder strToSign, String sMerchantKey) {
    String sign;
    try {
      //假设已排序字符串为strToSign
      //添加商户密钥
      strToSign.append("&").append(sMerchantKey);
      // 创建加密对象
      MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
      // 传入要加密的字符串,按指定的字符集将字符串转换为字节流
      messageDigest.update(strToSign.toString().getBytes(StandardCharsets.UTF_8));
      byte[] byteBuffer = messageDigest.digest();
      // 將 byte数组转换为16进制string
      sign = hexString(byteBuffer);
    }
    catch (Exception e) {
      sign = "";
      e.printStackTrace();
    }
    return sign;
  }
  /**
   * hexString
   *
   * @param baSrc byte[]
   * @return v
   */
  public static String hexString(byte[] baSrc) {
    if (baSrc == null) {
      return "";
    }
    int nByteNum = baSrc.length;
    StringBuilder sbResult = new StringBuilder(nByteNum * 2);
    for (byte b : baSrc) {
      char chHex;
      byte btHigh = (byte) ((b & 0xF0) >> 4);
      if (btHigh < 10) {
        chHex = (char) ('0' + btHigh);
      }
      else {
        chHex = (char) ('A' + (btHigh - 10));
      }
      sbResult.append(chHex);
      byte btLow = (byte) (b & 0x0F);
      if (btLow < 10) {
        chHex = (char) ('0' + btLow);
      }
      else {
        chHex = (char) ('A' + (btLow - 10));
      }
      sbResult.append(chHex);
    }
    return sbResult.toString();
  }
}
